import { constantRoutes } from '@/router'
import { getRouters } from '@/api/login'
import Layout from '@/layout/index.vue'
import { routerGenerator, asyncImportRoute } from '@/router/generatorRouters'

const state = {
  // 全部路由
  routes: [],
  // 后台获取到的路由
  addRoutes: [],
  keepAliveComponents: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_KEEPALIVE_COMPONENTS: (state, keepAliveComponents) => {
    state.keepAliveComponents = keepAliveComponents
  }
}

const actions = {
  async GenerateRoutes({ state, commit, rootState }) {
    try {
      const response = await getRouters()
      const routes = response.data
      // const routeList = routerGenerator(routes, 0)

      asyncImportRoute(routes)
      
      commit('SET_ROUTES', routes)

      return Promise.resolve(constantRoutes.concat(routes))
      
    } catch (error) {
      console.log("eeee", error)
      // @ts-ignore
      $message.error(error.data.message)
      return Promise.reject(error)
    }
  },
  SetKeepAliveComponents({ state, commit }, keepAliveComponents) {
    commit('SET_KEEPALIVE_COMPONENTS', keepAliveComponents)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
